package com.navi.service.impl;

import com.navi.service.IRabbitService;
import com.navi.util.LogUtil;
import com.rabbitmq.http.client.Client;
import com.rabbitmq.http.client.domain.BindingInfo;
import com.rabbitmq.http.client.domain.QueueInfo;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author Jay
 * @date 2018/5/9
 */
@Log
@Service
public class RabbitService implements IRabbitService {

    @Value("${spring.rabbitmq.host}")
    private String rabbitMQHost;
    @Value("${spring.rabbitmq.username}")
    private String rabbitMQUser;
    @Value("${spring.rabbitmq.password}")
    private String rabbitMQPassword;
    @Value("${spring.rabbitmq.http.port}")
    private String rabbitMQHttpPort;
    @Value("${spring.rabbitmq.queues}")
    private String queueNames;
    @Value("${spring.rabbitmq.exchange}")
    private String exchange;

    @Override
    public List<QueueInfo> getQueueInfo() {
        List<QueueInfo> queueInfoList = new ArrayList<>();
        Client client;
        try {
            String url = String.format("http://%s:%s/api/bindings", rabbitMQHost, rabbitMQHttpPort);
            client = new Client(url, rabbitMQUser, rabbitMQPassword);
            final List<String> queueStatusEntityList = client.getBindings().stream().filter(bind ->
                    StringUtils.equalsIgnoreCase(bind.getSource(), exchange)
            ).map(BindingInfo::getDestination).collect(Collectors.toList());

            url = String.format("http://%s:%s/api/queues", rabbitMQHost, rabbitMQHttpPort);
            client = new Client(url, rabbitMQUser, rabbitMQPassword);
            queueInfoList = client.getQueues().stream().filter(queueInfo ->
                    queueStatusEntityList.parallelStream().anyMatch(
                            qName -> StringUtils.equalsIgnoreCase(qName, queueInfo.getName())
                    )
            ).collect(Collectors.toList());

        } catch (MalformedURLException | URISyntaxException e) {
            LogUtil.pringStackTrace(e);
        }

        return queueInfoList;
    }
}
